package com.crm.service;

import com.crm.entity.Right;
import com.crm.entity.Role;
import com.crm.entity.User;
import com.crm.repository.RightRepository;
import com.crm.repository.RoleRepository;
import org.apache.shiro.web.filter.mgt.DefaultFilterChainManager;
import org.apache.shiro.web.filter.mgt.PathMatchingFilterChainResolver;
import org.apache.shiro.web.servlet.AbstractShiroFilter;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.context.support.WebApplicationContextUtils;

import javax.annotation.Resource;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

@Service("roleService")
public class IRoleServiceImpl implements IRoleService {

    @Resource
    RoleRepository roleRepository;
    @Resource
    RightRepository rightRepository;

    @Override
    @Cacheable(value = "roles", keyGenerator = "keyGenerator")
    public List<Role> findAllRoles() {
        return roleRepository.findAll();
    }

    @Override
    public List<Right> findAllRights() {
        return rightRepository.findAll();
    }

    @Override
    public List<Right> findRightsByRole(Role role) {
        return rightRepository.findRightsByRolesOrderByRightCode(role);
    }

    @Override
    public Role saveRole(Role role) {
        return roleRepository.save(role);
    }

    @Override
    public void deleteRoleById(Integer roleId) {
        roleRepository.deleteById(roleId);
    }

    @Override
    public void deleteRole(Role role) {
        roleRepository.delete(role);
    }

    @Override
    public Role getRole(Integer roleId) {
        return roleRepository.findById(roleId).get();
    }

    @Override
    public Page<Role> findRole(String roleName, Pageable pageable) {
        return roleRepository.findRolesByRoleNameLike("%" + roleName + "%", pageable);
    }

    @Override
    public Role findRoleByUsers(User user) {
        return roleRepository.findRolesByUsers(user);
    }

    @Override
    public Map<String, String> loadFilterChainDefinitions() {
        Map<String,String> filterChainDefinitionMap=new LinkedHashMap<String,String>();//必须使用LinkedHashMap
        filterChainDefinitionMap.put("/css/**", "anon");
        filterChainDefinitionMap.put("/fonts/**", "anon");
        filterChainDefinitionMap.put("/images/**", "anon");
        filterChainDefinitionMap.put("/js/**", "anon");
        filterChainDefinitionMap.put("/localcss/**", "anon");
        filterChainDefinitionMap.put("/localjs/**", "anon");
        // 无需认证
        filterChainDefinitionMap.put("/dologin", "anon");
        filterChainDefinitionMap.put("/logout", "logout");//注销过滤器，自动注销
        //动态授权
        List<Right> rights=findAllRights();
        for (Right right:rights) {
            if (right.getRightUrl()!=null&& !right.getRightUrl().trim().equals("")){
                filterChainDefinitionMap.put(right.getRightUrl(),"perms["+right.getRightCode()+"]");
            }
        }

        filterChainDefinitionMap.put("/**", "authc");//必须放在过滤器链最后面
        return filterChainDefinitionMap;
    }

    @Override
    public void reloadFilterChainDefinitions() {
        try {
            HttpServletRequest request=((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
            ServletContext servletContext=request.getSession().getServletContext();
            AbstractShiroFilter shiroFilter=(AbstractShiroFilter) WebApplicationContextUtils.
                    getRequiredWebApplicationContext(servletContext).getBean("getShiroFilterFactoryBean");
            synchronized (shiroFilter){
                //过滤管理器
                PathMatchingFilterChainResolver filterChainResolver=(PathMatchingFilterChainResolver)shiroFilter.getFilterChainResolver();
                DefaultFilterChainManager manager=(DefaultFilterChainManager)filterChainResolver.getFilterChainManager();
                //清空初始权限配置
                manager.getFilterChains().clear();
                //重新加载动态权限,配置验证规则
                Map<String,String> chains=loadFilterChainDefinitions();
                for (Map.Entry<String,String>entry:chains.entrySet()) {
                    String url=entry.getKey();
                    String chainDefinition=entry.getValue().trim().replace("","");
                    manager.createChain(url,chainDefinition);
                }
                System.out.println("更新权限成功!!");
            }
        }catch (Exception e){
            e.printStackTrace();
        }
    }

}
